#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QLabel>
#include <QVBoxLayout>
#include <QPushButton>
#include <QPushButton>
#include <QGraphicsDropShadowEffect>
#include "dht11.h"
#include "v4l2.h"
extern "C"{
#include "led_test.h"
}

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);


    server = new TcpServer;
    server_dht11 = new TcpServer;

    server->startServer(12580);
    server_dht11->startServer(12581);

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, this, [&]
    {/*
        int h, t;
        int ret = read_ht(h, t);
        if(ret)
        {
            QString data = QString("TEMP:%1,HUMI:%2").arg(h).arg(t);
            //qDebug() << data;
            server_dht11->sendData(data);
        }*/
        flag = true;
    });
    timer->start(100);

    connect(V4L2::get(), &V4L2::sigImage, this, [&](uchar *data)
    {
        if(flag)
        {
            flag = false;
            int h, t;
            int ret = read_ht(h, t);
            if(ret == 1)
            {
                QString data = QString("TEMP:%1,HUMI:%2").arg(h).arg(t);
                qDebug() << data;
                server_dht11->sendData(data);
            }
        }

        server->sendData((char *)data, 640*480*3);
        QImage img = QImage((uchar *)data,640,480,QImage::Format_RGB888);
        ui->label->setPixmap(QPixmap::fromImage(img));
    }, Qt::BlockingQueuedConnection);

    connect(server_dht11, &TcpServer::sigRecv, this, [&](QString data)
    {
        qDebug() << data;
        if(data.contains("ON"))
        {
            ::led_onOff(1);
        }
        else if(data.contains("OFF"))
        {
            ::led_onOff(0);
        }
    });

    init_dht11();
    init_light();
}

MainWindow::~MainWindow()
{
    delete ui;
}


